package com.example.controller;


import com.example.pojo.News;
import com.example.pojo.Result;
import com.example.service.NewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 *  新闻管理Controller
 */

@Slf4j
@RestController
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsService newsService;
    //private static Logger log = LoggerFactory.getLogger(NewsController.class);

    /**
     * 查询新闻列表
     * @return
     */
    @GetMapping()
    public Result list(){
        log.info("查询全部新闻列表");

        List<News> newsList = newsService.list();
        return Result.success(newsList);
    }

    /**
     * 新增新闻
     * @param news
     * @return
     */
    @PostMapping()
    public Result add( News news){
        log.info("新增一条新闻");
        newsService.add(news);

        return Result.success();
    }

    /**
     * 删除新闻
     * @param newsId
     * @return
     */
    @DeleteMapping("/{newsId}")
    public Result deleteById(@PathVariable Integer newsId){
        log.info("根据Id删除单条新闻");
        newsService.deleteById(newsId);
        return Result.success();
    }

    /**
     * 思路：图片上传至pics表，当前端提交表单时，再次请求得到pics表，并且将路径保存至news表，再次请求，清空pics表
     * @param pic
     * @return
     * @throws IOException
     */


    @PostMapping("/upload")
    public Result uploadPic(MultipartFile pic) throws IOException {
        log.info("文件上传：", pic);

        String originalFilename = pic.getOriginalFilename();

        int index = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);
        String newFileName = UUID.randomUUID().toString() + extname;
        log.info("新的文件名：{}", newFileName);
        //E:\workspace\download\vue-admin-template\src\assets\pic
        pic.transferTo(new File("E:\\workspace\\download\\vue-admin-template\\src\\assets\\pic\\"+newFileName));
        String path = newFileName;
        newsService.uploadPic(path);
        return Result.success(path);
    }

    public Result uploadsPic(){
        return Result.success();
    }

    @GetMapping("/listPic")
    public Result listPic(){
        log.info("查询全部图片列表");
        String[] picsList = newsService.picsList();
        return Result.success(picsList);

    }

    @DeleteMapping("/deletePic")
    public Result deletePic(){
        newsService.deletePic();
        return Result.success();
    }
}
